//
//  NetworkTools.swift
//  AFNetwork
//
//  Created by 李亚乐 on 15/12/8.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit
import AFNetworking

enum HMRequestMethod: String {
    case POST = "POST"
    case GET = "GET"
}

typealias HMRequestCallback = (success: AnyObject?, failure: NSError?) -> ()

/// 网络工具
class NetworkTools: AFHTTPSessionManager {
    
    // MARK: - 应用程序信息
    // 应用程序 ID
    private let appKey      = "910469949"
    private let appSecret   = "dc8104ab07c68087907324c9117fe84e"
//    private let appKey      = "3690335717"
//    private let appSecret   = "09cfc9024da37f90edcf3f5c7d42569a"
    private let redirectUrl = "http://www.baidu.com"
    //token=2.00Fvu4AC0LpOcz6965785b0f6UuraE
    
    /// 单例属性
    static let sharedTools: NetworkTools = { () -> NetworkTools in
        
        let tools = NetworkTools(baseURL: NSURL(string: ""))
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
}

// MARK: - 发微博相关方法
extension NetworkTools {
    /// 发布微博
    ///
    /// - parameter status:   微博内容
    /// - parameter finished: 完成回调
    func sendStatus(status: String, image: UIImage?, finished: HMRequestCallback) {
        
        //获取 token 字典
        var parameter = [String: AnyObject]()
        
        parameter["status"] = status
        
        if image == nil {
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        tokenRequest(HMRequestMethod.POST, URLString: urlString, parameters: parameter, finished: finished)
        } else {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let imageData = UIImagePNGRepresentation(image!)
            upload(HMRequestMethod.POST, URLString: urlString, parameters: parameter, data: imageData!, name: "pic", finished: finished)
        }
    }
}

// MARK: - 加载微博内容相关方法
extension NetworkTools {
    /// 加载微博数据
    ///
    /// - parameter finished: 完成的回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(since_id since_id: Int, max_id: Int, finished: HMRequestCallback) {

        //参数字典
        var parameter = [String: AnyObject]()
        // 判断是否下拉
        if since_id > 0 {
            parameter["since_id"] = since_id
        } else if max_id > 0 {  // 上拉参数
            parameter["max_id"] = max_id - 1
        }

        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        //发送网络请求
        tokenRequest(HMRequestMethod.GET, URLString: url, parameters: parameter, finished: finished)
    }
}

// MARK: - 用户信息相关方法
extension NetworkTools {
    /// 加载用户信息
    ///
    /// - parameter uid:         uid
    /// - parameter finished:    完成闭包 回调
    func loadUserInfo(uid: String, finished: HMRequestCallback) {
        
        //参数字典
        var parameters = [String: AnyObject]()
        
        //请求地址
        let url = "https://api.weibo.com/2/users/show.json"
        //参数字典添加一条 uid
        parameters["uid"] = uid
        tokenRequest(HMRequestMethod.GET, URLString: url, parameters: parameters, finished: finished)
    }
}

// MARK: - OAuth相关方法
extension NetworkTools {
    ///授权地址 计算型属性
    var OAuthURL: NSURL {
        /// 授权页面
        /// - see:[http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        return NSURL(string: urlString)!
    }
    
    /// 加载 AccessToken
    ///
    /// - parameter code:     授权码
    /// - parameter finised: 完成回调
    func loadAccessToken(code: String, finised: HMRequestCallback) {
        
        let url = "https://api.weibo.com/oauth2/access_token"
        
        let parameter = ["client_id": appKey,
                     "client_secret": appSecret,
                        "grant_type": "authorization_code",
                              "code": code,
                      "redirect_uri": redirectUrl]
        request(HMRequestMethod.POST, URLString: url, parameters: parameter, finished: finised)
        
        //测试返回数据
//        responseSerializer = AFHTTPResponseSerializer()
//        POST(url, parameters: parameter, success: { (NSURLSessionDataTask, result) -> Void in
//            print(result)
//            let json = NSString(data: result as! NSData, encoding:NSUTF8StringEncoding)
//            print(json)
//            }) { (_, Error) -> Void in
//                print(Error)
//        }
//Optional({"access_token":"2.00Fvu4AC0LpOcz6965785b0f6UuraE",
//              "remind_in":"157679999",
//              "expires_in":157679999,
//                  "uid":"1837966011"})
        //token=2.00Fvu4ACptQkBE8ba1fb5090SoN4NE&
        //uid=1837966011
    }
}

// MARK: - 封装AFN方法
extension NetworkTools {
    /// 向参数中拼接 token 字典
    ///
    /// - parameter parameter: 参数字典
    ///
    /// - returns: 是否追加成功
    private func appendToken(inout parameter: [String: AnyObject]?) -> Bool {
        //判断是否有 token
        guard let token = UserAccountViewModel.sharedUserAccount.Token else {
            
            return false
        }
        //判断字典是否有值
        if parameter == nil {
            parameter = [String: AnyObject]()
        }
        
        parameter!["access_token"] = token
        
        return true
    }
    
    /// 上传方法
    ///
    /// - parameter requestMethod:  POST / GET
    /// - parameter URLString:      接口地址
    /// - parameter parameters:    参数字典
    /// - parameter data:          图片二进制数据
    /// - parameter name:          name
    /// - parameter finished:      完成回调
    private func upload(requestMethod: HMRequestMethod, URLString: String, var parameters:[String: AnyObject]?,
        data: NSData, name: String, finished:HMRequestCallback) {
            
            if !appendToken(&parameters) {
                finished(success: nil, failure:  NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
                return
            }
        
        POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            
            formData.appendPartWithFileData(data, name: name, fileName: "xxx", mimeType: "application/octet-stream")

            }, success: { (_, result) -> Void in
                finished(success: result, failure: nil)
            }) { (_, error) -> Void in
                print(error)
                finished(success: nil, failure: error)
        }
    }

    
    /// token 网络请求方法
    ///
    /// - parameter requestMethod:  POST / GET
    /// - parameter URLString:     url 字符串
    /// - parameter parameters:    参数字典
    /// - parameter finished:      完成回调
    private func tokenRequest(requestMethod: HMRequestMethod,
        URLString: String,
        var parameters:[String: AnyObject]?,
        finished:HMRequestCallback) {
            
//            guard let token = UserAccountViewModel.sharedUserAccount.Token else {
            if !appendToken(&parameters) {
                let error =   NSError(domain: "cn.itcast.error",
                                        code: -1001,
                                    userInfo: ["message": "token 为空"])
                
                finished(success: nil, failure:error)
                return
            }
            
            request(requestMethod, URLString: URLString, parameters: parameters, finished: finished)
    }
    
    /// 网络请求
    ///
    /// - parameter requestMethod: GET/POST
    /// - parameter URLString:     URLString
    /// - parameter parameter:     参数字典
    /// - parameter finished:      完成回调 成功/失败
    private func request(requestMethod: HMRequestMethod,
        URLString: String,
        parameters:[String: AnyObject]?,
        finished:HMRequestCallback) {
            //成功回调
            let successClosure = {(dataTask:NSURLSessionDataTask?, result:AnyObject?) -> Void in
                finished(success: result, failure: nil)
            }
            //失败回调
            let failureClosure = { (dataTask:NSURLSessionDataTask?, error:NSError) -> Void in
                print(error)
                finished(success: nil, failure: error)
            }
        
            if requestMethod == HMRequestMethod.GET {
                GET(URLString, parameters: parameters, success: successClosure, failure: failureClosure)
            } else if requestMethod == HMRequestMethod.POST {
                POST(URLString, parameters: parameters, success: successClosure, failure: failureClosure)
            }
    }
    
}